package lv.dysnomia.server.entities;

import java.util.{List=>JavaList};

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import lv.dysnomia.portal.web.PMF;

object SongDAO {

  def getSongByLabel(label: String): Song = {
    val emptySong = new Song
    val pm = PMF.getInstance.getPersistenceManager
    val song: Song = try {
      val query: Query = pm.newQuery((new Song).getClass)
      query.setFilter("label == labelParam")
      query.setOrdering("version desc")
      query.declareParameters("String labelParam")
      val results: JavaList[Song] = query.execute(label).asInstanceOf[JavaList[Song]]
      if (results != null && results.size() > 0) {
    	  val result = results.get(0)
    	  if (result != null) {
    	 	  result.getLilypond
    	  }
    	  result
      }
      else emptySong
    } catch {
      case e: Exception => { println(e.toString); emptySong }
    }
    finally {
      pm.close();
    }
    return song
  }

  def getSongs(): JavaList[Song] = {
    val pm = PMF.getInstance.getPersistenceManager
    val songs: JavaList[Song] = try {
      val query = pm.newQuery((new Song).getClass)
      val result = query.execute.asInstanceOf[JavaList[Song]]
      result.size; result
    } catch {
      case e: Exception => { println(e.toString); Nil.asInstanceOf[JavaList[Song]] }
    }
    finally {
      pm.close();
    }
    return songs
  }
  
  def getSongs(offset:Int): JavaList[Song] = {
    val pm = PMF.getInstance.getPersistenceManager
    val songs: JavaList[Song] = try {
      val query = pm.newQuery((new Song).getClass)
      query.setRange(offset, offset+2)
      val result = query.execute.asInstanceOf[JavaList[Song]]
      result.size; result
    } catch {
      case e: Exception => { println(e.toString); Nil.asInstanceOf[JavaList[Song]] }
    }
    finally {
      pm.close();
    }
    return songs	  
  }

  def save(s: Song): Unit = {
    val pm = PMF.getInstance.getPersistenceManager
    try {
      pm.makePersistent(s)
    } finally {
      pm.close()
    }
  }

  def removeByLabel(label: String): Long = {
    val pm = PMF.getInstance.getPersistenceManager
    try {
      val query = pm.newQuery((new Song).getClass)
      query.setFilter("label == labelParam")
      query.declareParameters("String labelParam")
      query.deletePersistentAll(label)
    } finally {
      pm.close()
    }
  }

  def removeAll(): Long = {
    val pm = PMF.getInstance.getPersistenceManager
    try {
      val query = pm.newQuery((new Song).getClass)
      query.deletePersistentAll()
    } finally {
      pm.close()
    }
  }
}
